import { Component, OnInit, ViewEncapsulation, Input, OnDestroy } from '@angular/core';
import { ElasticsearchService } from './../../services/elasticsearch.service';
import { RestService } from './../../services/rest.service';
import { DataService } from '../../services/data.service';
import { Subscription } from 'rxjs/Rx';

import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
  selector: 'app-train-chart',
  templateUrl: './train-chart.component.html',
  styleUrls: ['./train-chart.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class TrainChartComponent implements OnInit, OnDestroy {
  @Input() tableId: string;

  subscription: Subscription;
  subscriptionEvent: Subscription;

  table: any;

  echartsInstance: any;
  chartOptions: any;

  savedChartData: any;

  constructor(public restService: RestService,
              public dataService: DataService) {
    this.subscription = this.dataService.trend$.subscribe(input => {
      if (this.echartsInstance) {
        this.refresh(input);
      } else {
        this.savedChartData = input;
        console.log('Chart data was received while chart is not ready.');
      }
    });

    this.subscriptionEvent = this.dataService.data$.subscribe(event => {
      if (event === 'RefreshChart') {
        if (this.echartsInstance) {
          this.echartsInstance.showLoading();
        }
      }
    });
  }

  onChartInit(ec) {
    this.echartsInstance = ec;
    ec.setOption(this.chartOptions);
    ec.showLoading();

    if (this.savedChartData) {
      this.refresh(this.savedChartData);
    }
  }

  resizeChart() {
    if (this.echartsInstance) {
      this.echartsInstance.resize();
    }
  }

  initChart() {
    this.chartOptions = {
      title: {
        x: 'center',
        y: 'bottom',
        text: this.table.name
      },
      tooltip : {
        trigger: 'axis',
        axisPointer: {
          animation: false
        }
      },
      legend: {
        orient: 'horizontal',
        x: 'center',
        y: 'top',
        data: this.buildChartLegend()
      },
      toolbox: {
        show: true,
        feature: {
        /*
          dataZoom: {show: true},
          restore: {show: true},
        */
          saveAsImage: {show: true, type: 'png'}
        }
      },
      calculable: false,
      grid: {
      },
      xAxis : this.buildXaxis(),
      yAxis : [
        {
          type : 'value',
          splitArea: {show: true},
          name: ''
        }
      ],
      series : this.buildSeries()
    };
  }

  buildChartLegend() {
    const legends = [];
    this.table.elements.forEach(item => {
      legends.push(item.name);
    });

    return legends;
  }

  buildXaxis() {
    const xaxis = {
      type: 'time'
    };

    return xaxis;
  }

  buildSeries() {
    const series = [];
    this.table.elements.forEach(item => {
      series.push({
        name: item.name,
        type: 'line',
        showSymbol: false,
        data: []
      });
    });

    return series;
  }

  refresh(input) {
    this.echartsInstance.hideLoading();

    const series = [];
    this.table.elements.forEach(item => {
      series.push({
        name: item.name,
        data: []
      });
    });

    input.data.forEach(singleData => {
      const row = singleData['_source'];
      const updatedTime = this.restService.getUpdatedDateTime(row);

      this.table.elements.forEach(item => {
        const index = _.findIndex(series, {name: item.name});
        if (index !== -1 && !_.isNil(row[item.id])) {
          const dataPoint = [updatedTime, row[item.id]];
          series[index].data.push(dataPoint);
        }
      });
    });

    this.echartsInstance.setOption({
      series: series
    });

    if (this.savedChartData) {
      this.savedChartData = null;
    }
  }

  ngOnInit() {
    this.table = this.restService.getTable(this.tableId);
    this.initChart();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    this.subscriptionEvent.unsubscribe();
  }
}
